<template>
	<view>
		<mc-framework navTitle="MES工控机" @changeLevel="changeLevel">
			<template #content>
				<view class="content" style="height: 100%;">
					<view class="contentBox">
						<view class="container">

							<uni-forms ref="baseForm" :modelValue="baseFormData">
								<view class="form-item-row">
									<u-cell icon="setting-fill" title="申请人填写" style="width: 100%;"></u-cell>
									<uni-forms-item v-show="titleShowTitle=='设备异常'" label="故障机台:" label-width="auto">
										<view class="uni_forms_item_view" @click="openBaseScreen('机台')">
											<text v-if="!baseFormData.EquipmentName"
												class="u_text">{{FormData.EquipmentName}}</text>
											<text v-else>{{baseFormData.EquipmentName}}</text>
										</view>
									</uni-forms-item>
									<uni-forms-item v-show="titleShowTitle=='模具异常'" label="故障模具:" label-width="auto">
										<view class="uni_forms_item_view" @click="openBaseScreen('模具')">
											<text v-if="!baseFormData.MoludName"
												class="u_text">{{FormData.MoludName}}</text>
											<text v-else>{{baseFormData.MoludName}}</text>
										</view>
									</uni-forms-item>
									<!-- FaultTypeID -->
									<uni-forms-item label="故障类型:" label-width="auto" disabled>
										<input v-model="baseFormData.FaultTypeName" type="text" placeholder="请选择故障类型"
											disabled />
										<text class='text' @click="addFaultTypeName"></text>
									</uni-forms-item>
									<uni-forms-item label="故障原因:" label-width="auto" disabled>
										<input v-model="baseFormData.FaultName" type="text" placeholder="请选择故障原因"
											disabled />
										<text class='text' @click="addFaultName"></text>
									</uni-forms-item>
									<uni-forms-item label="故障描述:" label-width="auto" disabled>
										<input v-model="baseFormData.GZContent" type="text" placeholder="请输入故障描述" />
									</uni-forms-item>
									<uni-forms-item label="申报人:" label-width="auto">
										<input v-model="baseFormData.Declarer" type="text" disabled placeholder="申报人" />
									</uni-forms-item>
									<uni-forms-item label="现场照片:" label-width="auto" style="width: 100%;"
										class="uni_forms_item">
										<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic" multiple
											:maxCount="5" :previewFullImage="true"></u-upload>
									</uni-forms-item>
								</view>
							</uni-forms>

						</view>

					</view>

					<view class="DetailsbottomBtns">

						<button class="button1" block @click="submit" style="z-index: 99;">
							{{changeButton}}
						</button>
						<button class="button2" block @click="devicerepair" v-show="titleShow">
							维修
						</button>
					</view>
					<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show=false'
						@confirm='pickerConfirm'></u-datetime-picker>
					<u-action-sheet :actions="FaultNameList" :show="FaultNameShow" @select="FaultNameClick"
						@close="FaultNameShow=false"></u-action-sheet>
					<u-toast ref="uToast"></u-toast>
					<u-action-sheet :actions="FaultTypeNameList" :show="FaultTypeNameShow" @select="FaultTypeNameClick"
						@close="FaultTypeNameShow=false"></u-action-sheet>
					<u-toast ref="uToast"></u-toast>



					<u-popup :show="popup_logout" mode="center" :closeOnClickOverlay="false" :round="4">
						<view class="popup-content">
							<view class="popup-content_close x-c">
								<uni-icons type="closeempty" color="#999" size="20"
									@click='popup_logout = false'></uni-icons>
							</view>
							<view class="x-c title">
								<text>{{popuptitle}}</text>
							</view>
							<view class="contentView">
								<text>{{popupcontent}}</text>
							</view>
							<view class="btnBox x-ac">

								<u-button type="primary" text="确定" @click="confirmClick"></u-button>
							</view>
						</view>
					</u-popup>

				</view>
			</template>

		</mc-framework>
	</view>
</template>


<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/mes/common/base.js';


	export default {
		data() {
			return {
				popup_logout: false,
				popuptitle: '',
				popupcontent: '',
				DImgs: [],
				serverIP: '',
				FaultTypeNameShow: false,
				FaultTypeNameList: [],
				FaultNameShow: false,
				FaultNameList: [],
				FormData: {
					MoludName: '请选择故障模具',
					EquipmentName: '请选择故障机台'
				},
				baseFormData: {
					MoludID: '',
					MoludName: '',
					FaultID: '',
					FaultName: '',
					FaultTypeID: '',
					FaultTypeName: '',
					BillNO: '',
					StartSingleDate: '',
					ProductName: '',
					StartQty: '',
					EquipmentName: '',
					EquipmentCode: '',
					EquipmentID: '',
					MoludName: '',
					FlowOrder: '',
					ProcedureName: '',
					FWorkshopName: '',
					IsStart: '',
					StartEmplID: '',
					StartEmplName: '',
					QCEmplID: '',
					QCEmplName: '',
					GZQPicture: [],
					Declarer: '',
				},
				DImgs: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				TimeName: '',
				show: false,
				value1: Number(new Date()),

				changeName: '',
				changeButton: '保存',
				titleShow: false,
				titleShowTitle: '',
			};
		},

		onLoad(onload) {
			var that = this
			if (onload.item) {
				var item = JSON.parse(onload.item)
				if (item.title) {
					this.titleShowTitle = item.title
				}
				this.queryList(item.FaultDocID)
			} else {
				if (onload.obj) {
					var obj = JSON.parse(onload.obj)
					that.baseFormData = obj

				}
				this.titleShowTitle = onload.titleName
				this.baseFormData.MoludID = 0
				this.baseFormData.Declarer = this.$store.state.UserInfo.UserName
				this.baseFormData.EquipmentName = this.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentName
				this.baseFormData.EquipmentCode = this.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentCode
				this.baseFormData.EquipmentID = this.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentID

			}
			if (that.titleShowTitle == '设备异常') {
				that.baseFormData.FaultTypeName = '设备故障'
				that.baseFormData.FaultTypeID = 1

			} else if (that.titleShowTitle == '模具异常') {
				that.baseFormData.FaultTypeName = '模具故障'
				that.baseFormData.FaultTypeID = 2

			} else if (that.titleShowTitle == '工艺异常') {
				that.baseFormData.FaultTypeName = '工艺故障'
				that.baseFormData.FaultTypeID = 3

			}
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {
			this.getValue
			this.getList
		},
		methods: {

			confirmClick() {

				this.popup_logout = false
			},
			getList() {

			},

			getValue(e) {
				var that = this
				if (e != '返回') {
					if (e.type == '机台') {
						that.baseFormData.EquipmentName = e.EquipmentName
						that.baseFormData.EquipmentID = e.EquipmentID
					} else if (e.type == '模具') {
						that.baseFormData.MoludID = e.MoludID
						that.baseFormData.MoludName = e.MoludCode
					}
					that.$forceUpdate()
				}
			},
			openBaseScreen(str) {

				var that = this;
				var obj;
				if (str == '机台') {
					obj = {

						type: str,
						cmd: 'getEquipment',
						param: {}
					}
				} else if (str == '模具') {
					obj = {

						type: str,
						cmd: 'Droplist_Molud',
						param: {
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				}

				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},
			devicerepair() {
				let obj
				let url
				let routes = getCurrentPages();
				var item = {
					FaultName: this.baseFormData.FaultName,
					GZContent: this.baseFormData.GZContent,
					EquipmentName: this.baseFormData.EquipmentName,
					EquipmentID: this.baseFormData.EquipmentID,
				}
				if (this.titleShowTitle == '设备异常') {
					obj = {
						length: routes.length + 1,
						Name: '设备维修详情',
						APPFunID: '设备维修详情'
					}
					url = `/mes/device/devicerepairDetail?item=${JSON.stringify(item)}`
				} else if (this.titleShowTitle == '模具异常') {
					obj = {
						length: routes.length + 1,
						Name: '模具维修详情',
						APPFunID: '模具维修详情'
					}
					url = `/mes/mold/moldepairDetail?item=${JSON.stringify(item)}`
				}

				let newData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
				newData.push(obj);

				this.$store.commit('GuyueModule/ChangeAndSetStateData', {
					Name1: 'ModuleData_select',
					data: newData
				})

				console.log(item);
				uni.navigateTo({
					url: url,
					animationType: 'slide-in-right', // 动画类型
					animationDuration: 300 // 动画时长
				});

			},
			FaultTypeNameClick(e) {
				var that = this
				console.log(e);
				that.baseFormData.FaultTypeID = e.FaultTypeID
				that.baseFormData.FaultTypeName = e.FaultTypeName
				that.FaultTypeNameShow = false
				that.$forceUpdate()
			},
			addFaultTypeName() {
				var that = this
				this.Request.request('getPKGFaultType', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultTypeName)
						that.FaultTypeNameList = ret.data.ds
						that.FaultTypeNameShow = true

					}
				})
			},
			FaultNameClick(e) {
				var that = this
				that.baseFormData.FaultID = e.FaultID
				that.baseFormData.FaultName = e.name
				that.FaultNameShow = false
				that.$forceUpdate()
			},
			addFaultName() {
				var that = this
				this.Request.request('getPKGFault', {
					FaultTypeID: that.baseFormData.FaultTypeID
				}, (ret) => {
					console.log(JSON.stringify(ret));
					if (ret.status == 200) {
						ret.data.ds.map(item => item.name = item.FaultName)
						that.FaultNameList = ret.data.ds
						that.FaultNameShow = true

					}
				})
			},

			deletePic(event) {
				this.DImgs.splice(event.index, 1);
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://' + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '现场照片',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							resolve(data.data)
						}
					});
				})
			},


			changebuttons(ID) {
				if (ID == 0) {
					this.changeButton = '开工'
				} else {
					this.changeButton = '保存'

				}
			},

			// 获取时间
			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				this.baseFormData.StartSingleDate = time
				this.show = false
				this.$forceUpdate()
			},

			submit() {
				var that = this;
				var BiType
				var msg
				var show = true
				if (that.baseFormData.FaultTypeID == 1) {
					BiType = 'SBYC'
				} else if (that.baseFormData.FaultTypeID == 2) {
					BiType = 'MJYC'
				} else if (that.baseFormData.FaultTypeID == 3) {
					BiType = 'GYYC'
				}

				if (that.baseFormData.FaultName == '' || that.baseFormData.FaultName == null) {
					msg = '请输入故障原因'
					show = false
				} else if (that.baseFormData.GZContent == '' || that.baseFormData.GZContent == null) {
					msg = '请输入故障描述'
					show = false
				}

				if (show) {
					const prefix = 'http://' + that.Request.serverIP();

					that.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					});

					var obj = {
						FaultName: that.baseFormData.FaultName,
						FaultTypeID: that.baseFormData.FaultTypeID,
						MoludID: that.baseFormData.MoludID,
						EquipmentID: that.baseFormData.EquipmentID,
						Declarer: that.baseFormData.Declarer,
						GZContent: that.baseFormData.GZContent,
						FilePath1: that.DImgs.map(item => item.url).join(','),
						BillType: BiType,
						FaultDocID: that.baseFormData.FaultDocID ? that.baseFormData.FaultDocID : 0
					}

					console.log(obj);
					that.Request.request('saveFaultDoc', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							setTimeout(() => {
								that.queryList(ret.data.ds[0].FaultDocID)
							}, 1000)

						}
					})

				} else {
					that.popuptitle = '报错'
					that.popupcontent = msg
					that.popup_logout = true
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getFaultDocDetail', {
						FaultDocID: id
					}, (ret) => {
						console.log(ret.data);
						var stringArray = ret.data.ds[0].FilePath1.split(',')
						if (stringArray[0] != '' && stringArray.length > 0) {
							that.DImgs = stringArray.map(item => ({
								url: 'http://' + that.Request.serverIP() + item.trim()
							}));
						}
						that.baseFormData = ret.data.ds[0]
						if (that.baseFormData.FaultDocID) {
							that.titleShow = true
						}
						that.$forceUpdate()
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			// 跳转tag
			changeLevel(data, row) {
				let routes = getCurrentPages(); //当前页面栈
				let backIndex = routes.length - row.length; // 计算返回页面栈数
				if (backIndex == 1) {
					let prevPage = routes[routes.length - 2]
					prevPage.$vm.getList()
				}
				uni.navigateBack({
					delta: backIndex
				})
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";


	.form-item-row {
		display: flex;
		flex-wrap: wrap;

		.uni-forms-item {
			width: 46%;
			margin: 0.3% 2%;

			input {
				height: 100%;
				width: 36vw;
				border-bottom: 2px solid #51d0d0;
			}

			.uni_forms_item_view {
				width: 36vw;
			}
		}

		.uni_forms_item {
			width: 100%;
			display: flex;
			align-items: center;

			.u-upload {
				width: 85vw;
				float: right;
			}
		}


	}
</style>